package com.woniu.common.utils;

import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson2.JSONObject;
import com.woniu.common.dto.UserDTO;
import org.springframework.http.server.reactive.ServerHttpRequest;

import javax.servlet.http.HttpServletRequest;

public class UserUtil {

    public static final String TOKEN = "authentication";
    public static final String USER = "user";

    public static UserDTO getUser(HttpServletRequest request) {
        String token = request.getHeader(TOKEN);
        return getUserDTO(token);
    }

    public static UserDTO getUser(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(TOKEN);
        return getUserDTO(token);
    }



    public static UserDTO getUser(String token) {
        return getUserDTO(token);
    }

    private static UserDTO getUserDTO(String token) {
        String json = JWTUtil.parseToken(token).getPayload(USER).toString();
        return  JSONObject.parseObject(json, UserDTO.class);

    }
}
